package com.ysu.zyw.common.util;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.Assert;

/**
 * JsonUtil provide an set of operation to json.
 * <p>
 * Created by ZeRur on 2016/1/17.
 *
 * @author yaowu.zhang
 */
public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * transform an object to json string.
     *
     * @param object object
     * @return json string
     * @throws JsonProcessingException
     */
    public static String serialize(Object object) throws JsonProcessingException {
        Assert.notNull(object, "null object is not allowed");
        return objectMapper.writeValueAsString(object);
    }

    /**
     * transaform an json string to an object.
     *
     * @param text  json string
     * @param clazz type the json string is convert to
     * @param <T>   type the json string is convert to
     * @return object
     * @throws IOException
     */
    public static <T> T deserialize(String text, Class<T> clazz) throws IOException {
        Assert.hasText(text, "empty text is not allowed");
        Assert.notNull(clazz, "null clazz is not allowed");
        return objectMapper.readValue(text, clazz);
    }

}
